﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeml.Document;
using System.Drawing;
using System.Drawing.Drawing2D;
using Mpi.Common;

namespace Xeml.Visualization
{
    public static class HeatMapper
    {

        public static Brush ValueToBrush(TimeRegionPixelMapper pxMapper, DynamicValueBase vb, double min, double max, Color minColor, Color maxColor)
        {
            if (min == max)
                return new SolidBrush(minColor);

            int x = pxMapper.MapPoint(vb.Time);
            int w = 1000;
            ColorBlend cb = null;
            if (vb is Cycle)
            {
                Cycle c = vb as Cycle;
                w = pxMapper.MapPoint(c.Length);
                cb = new ColorBlend();
                List<float> temp = new List<float>();
                List<Color> colors = new List<Color>();
                temp.Add(0f);
                float lastVal = 0f;
                float totalLength = (float)c.Length.TotalMilliseconds;
                for (int i = 0; i < c.Values.Count; i++)
                {
                    lastVal += (float)c.Values[i].Time.TotalMilliseconds;
                    float res = lastVal / totalLength;

                    if (res < 1f)
                    {
                        temp.Add(lastVal / totalLength);
                        temp.Add((lastVal / totalLength) + 0.000000000000001f);
                    }
                    else
                        temp.Add(1f);

                    Color col = ColorMapper.MapValue((decimal)(c.Values[i] as DynamicValue).DoubleValue, (decimal)min, (decimal)max, minColor, maxColor);
                    colors.Add(col);
                    colors.Add(col);
                }
                cb.Positions = temp.ToArray();
                cb.Colors = colors.ToArray();

                Rectangle r = new Rectangle(x, 0, w, 20);
                LinearGradientBrush br = new LinearGradientBrush(r, Color.Black, Color.Black, 0, false);
                br.InterpolationColors = cb;
                return br;
            }
            else
            {
                DynamicValue v = vb as DynamicValue;
                SolidBrush br = new SolidBrush(ColorMapper.MapValue((decimal)v.DoubleValue, (decimal)min, (decimal)max, minColor, maxColor));
                return br;
            }
        }
    }
}
